package com.aabte.hystrixlearn.hystrix.command;

import com.aabte.hystrixlearn.common.HttpClientUtil;
import com.aabte.hystrixlearn.model.ProductInfo;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixObservableCommand;
import lombok.extern.slf4j.Slf4j;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

import java.util.Arrays;

/**
 * @author Daniel
 */
@Slf4j
public class GetProductInfosCommand extends HystrixObservableCommand<ProductInfo> {

    private final Long[] productIds;

    public GetProductInfosCommand(Long[] productIds) {
        super(HystrixCommandGroupKey.Factory.asKey("GetProductInfosCommand"));
        this.productIds = productIds;
    }

    @Override
    protected Observable<ProductInfo> construct() {
        log.info("Start construct. productIds: {}", Arrays.asList(productIds));
        Observable<ProductInfo> productInfoObservable = Observable.create(new Observable.OnSubscribe<ProductInfo>() {
            @Override
            public void call(Subscriber<? super ProductInfo> observer) {
                try {
                    for (Long productId : productIds) {
                        String url = "http://127.0.0.1:8080/product/" + productId;
                        ProductInfo productInfo = HttpClientUtil.getInstance().getForObject(url, ProductInfo.class);
                        observer.onNext(productInfo);
                    }
                    observer.onCompleted();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).subscribeOn(Schedulers.io());
        log.info("End construct. productIds: {}", Arrays.asList(productIds));
        return productInfoObservable;
    }
}
